<?php
/**
 * @file
 * Controls database operations on the dbIndividual table.
 *
 * Copyright 2011 by ....  This program is part of Donate.
 * Donate is free software.  It comes with absolutely no warranty.
 * You can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation
 * (see <http://www.gnu.org/licenses/ for more information).
 *
 * @version March 5th 2011
 * @author Matthew Wakim
 */

include_once('dbConnect.php');
include_once('../model/Individual.php');

class dbIndividual {

	/**
	 * Creates individual table in the database.
	 */
	static function createTable() {
		$query =("CREATE  TABLE IF NOT EXISTS individual (
                donorID   INT 		NOT NULL ,
                firstName VARCHAR(20) NULL ,
                lastName  VARCHAR(20) NULL ,
                CONSTRAINT pk_individual PRIMARY KEY (donorID),
                CONSTRAINT fk_individual_donor FOREIGN KEY (donorID)
                  REFERENCES donor (donorID)ON DELETE CASCADE ON UPDATE CASCADE
          );
    ");
		connect();
		$result = mysql_query($query);
		mysql_close();
		if ($result == false) {
			echo mysql_error( );
			return false;
		}
		// Previous query was successful.
		return true;
	}

	/**
	 * Gets donorID  based on donorID???? - What's the purpose of this function???
	 * @param integer $i The donorID value based on which searching is done.
	 * @return donorID value.
	 */
	function getdonorID($i) {
		$result = mysql_query("SELECT donorID FROM Individual WHERE donorID='$i'");
		$row = mysql_fetch_row($result);
		return $row[0];
	}

	/**
	 * Gets an instance from the individual table based on donorID.
	 * Only one instance is expected, if donorID exists.
	 * @param integer $id The donorID based on which searching is done.
	 * @param string or array $output The output from this call is one of the
	 * following three values:
	 *    An error message about failing to perform a SELECT query.
	 *    An error message about not finding any instance or finding multiple
	 *    instances for the given donorID.
	 *    An array that has all the attribute values of an Individual instance.
	 *
	 * Notice that when this function is called, $output is passed by reference.
	 * @return TRUE if an error message is returned via reference parameter $output.
	 * FALSE if an array with attribute values is returned via reference parameter
	 * $output.
	 */
	public static function getAllByID($id, &$output) {
		$query = sprintf("SELECT firstName, lastName FROM individual WHERE donorID=%d",
		$id);
		// printf("->Query: %s<br />", $query);

		connect( );
		$result = mysql_query($query);
		mysql_close( );

		if ($result == false) {
			$output = sprintf("%s", mysql_error());
			return false;
		}
		//process result and print out warning or attribute values
		return dbIndividual::checkForOneInstance($result, $id, $output);
	}

	/**
	 * Stores individual table in array $allIndArray
	 * @param array $allIndArray
	 */
	static function getAllIndividuals(&$allIndArray) {
		connect( );
		$result = mysql_query("SELECT donorID, lastName, firstName FROM Individual");
		mysql_close( );
		if ($result == false) {
			return false;
		}
		$numOfRows = mysql_num_rows($result);
		for($i = 0; $i < $numOfRows; $i++){
			$currentRow = mysql_fetch_assoc($result);
			$allIndArray[ ] = $currentRow;
		}
		return true;
	}
	
	/**
	 * @author Matt V
	 * @param array $allIndArray
	 * Returns individuals given id
	 */
	static function getIndividualById($id) {
		connect( );
		$result = mysql_query("SELECT donorID, lastName, firstName FROM Individual WHERE donorID='$id'");
		mysql_close( );
		if ($result == false) {
			return false;
		}
		$numOfRows = mysql_num_rows($result);
		$indArray = array();
		for($i = 0; $i < $numOfRows; $i++){
			$currentRow = mysql_fetch_assoc($result);
			$indArray = $currentRow;
		}
		return $indArray;
	}
	
	/**
	 * @author Matt Vartanian
	 * Gets individuals by last name
	 * @param $chosenLetter
	 */
	static function getIndividualsByLastName($letterChosen) {
		connect( );
		$result = mysql_query("SELECT donorID, lastName, firstName FROM Individual
		WHERE lastName LIKE '$letterChosen%'");
		mysql_close( );
		if ($result == false) {
			return false;
		}
		$allIndArray = array( );
		$numOfRows = mysql_num_rows($result);
		for($i = 0; $i < $numOfRows; $i++){
			$currentRow = mysql_fetch_assoc($result);
			$allIndArray[ ] = $currentRow;
		}		
		return $allIndArray;
	}
	
	/**
	 * Checks if in the SELECT query result from quering the individual table based
	 * on a primary key value has no or multiple instances OR exactly one instance.
	 * @param resource $resut The SELECT query result when looking for instances
	 * with the given primary key value.
	 * @param integer $id The primary key value based on which SELECT was made.
	 * @param $output Either a string with an error message or an array with the
	 * attribute values (result of a mysql_fetch_assoc( ) call. This parameter is
	 * passed by reference.
	 * @return TRUE if exactly one instance is found. FALSE, otherwise.
	 */
	private static function checkForOneInstance($result, $id, &$output)
	{
		//Local variables are initialized.
		//Think positively about what this checking returns :-) and set $errorStatus
		//to initial value false
		$errorStatus = false;

		$howMany = mysql_num_rows($result);
		// printf("-->Found %d instance(s) for donorID=%d.<br />", $howMany, $id);
		switch ($howMany) {
			case 0:
				$output = sprintf("No Individual instance with ID=%d was found.",
				$id);
				$errorStatus = true;
				break;
			case 1:
				//mysql_fetch( ) DOES NOT return primary key values!
				$output = mysql_fetch_assoc($result);
				$errorStatus = false;
				break;
			default:
				$output = sprintf("There are multiple Individual instances
                           with ID=%d.", $id);
				$errorStatus = true;
				break;
		}
		return $errorStatus;
	}

	/** this function gets the lastname field from its location
	 */
	function getlastname($i) {
		$result = mysql_query("SELECT lastname FROM Individual WHERE donorID='$i'");
		$row = mysql_fetch_row($result);
		return $row[0];
	}

	static function addIndividualByFields($donorID, $firstName, $lastName)
	{
		$i = new Individual($donorID, $firstName, $lastName);
		$result = dbIndividual::addIndividual($i);
		if ($result == false) {
			die ("Individual could not be updated with specified information.<br />");
		}
	}

	static function verifyInsertedIndividual($id)
	{
		$output = "";
		$error = dbIndividual::getAllByID($id, $output);
		if ($error == true) {
			printf("%s<br />", $output);
		}
		else {
			$ind = new Individual($id, $output['firstName'], $output['lastName']);
			printf("Inserted: Individual with ID=%d has %s.<br />", $id, $ind->printAllAttributes( ));
		}
	}

	/**
	 * Inserts an individual instance in the individual table.
	 * @param Individual $v The individual instance that's inserted.
	 * @return TRUE if insertion succeeds. FALSE otherwise.
	 */

	static function addIndividual($v) {
		if (!$v instanceof Individual) {
			echo ("Invalid argument. Must be of type Individual.<br />");
			return false;
		}
		// Compose the INSERT INTO query srting. Primary key value is missing.
		// Database server automatically generates a unique ID for the primary Key.
		$query = sprintf("INSERT INTO individual VALUES(%d, '%s', '%s')",
		$v->getDonorID(),
		$v->getFirstName(),
		$v->getLastName()
		);
		connect( );
		$result = mysql_query($query);
		mysql_close( );
		if ($result == false) {
			echo mysql_error();
			return false;
		}
		// query was successful.
		return true;
	}
	
  /**
   *  this function deletes an individual from the database
   */
  static function deleteIndividual($i) {
      //$i = $v->getdonorID();
      //return mysql_query("DELETE FROM Individual WHERE donorID='$i'");
      connect( );
      $result = mysql_query("DELETE FROM Individual WHERE donorID='$i'");
      mysql_close( );
  }	
}
?>